﻿//tracker configation

/// <reference path="vswd-ext_2.2.js" />
Ext.ns('TrackerDefine');
TrackerDefine.version = 'Beta 1';
var g_DicTrackerAlarmDefine = new Dictionary();
var g_DicTrackerStateDefine = new Dictionary();

var globalalarmdefinestore = new Ext.data.JsonStore({
    url: 'HandlerTrackerDefine',
    autoLoad: true,
    root: 'data',
    fields: [
                'sssid',
                'TrackerName',
                { name: 'DefineID', type: 'integer' }
                , { name: 'AlarmType', type: 'integer' }
                , 'Expression',
                , { name: 'IsEmergency', type: 'boolean' }
                , { name: 'SendEmail', type: 'boolean' }
            ]
     , baseParams: {
         sssids: '',
         eventtype: 'search',
         eventobject: 'alarm',
         key: ''
     }
});

globalalarmdefinestore.on('load', function(store, records) {
    for (var i = 0; i < records.length; i++) {
        var record = records[i];
        var sssid = record.get('sssid');
        var alarmtype = record.get('AlarmType');
        if (g_DicTrackerAlarmDefine.ContainsKey(sssid)) {
            var tmpdic = g_DicTrackerAlarmDefine.Item(sssid);
            tmpdic.Add(alarmtype, record);
        }
        else {
            var tmpdic = new Dictionary();
            tmpdic.Add(alarmtype, record);
            g_DicTrackerAlarmDefine.Add(sssid, tmpdic);

        }
    }
});

var globalstatedefinestore = new Ext.data.JsonStore({
    url: 'HandlerTrackerDefine',
    autoLoad: true,
    root: 'data',
    fields: [
            'sssid',
            'TrackerName',
            { name: 'DefineID', type: 'integer' },
            { name: 'BitIndex', type: 'integer' },
            'Expression',
            { name: 'ControlType', type: 'integer' },
            'true_exp',
            'false_exp',
            'true_icon',
             'false_icon'
        ]
    , baseParams: {
        sssids: '',
        eventtype: 'search',
        eventobject: 'state',
        key: ''
    }
});

globalstatedefinestore.on('load', function(store, records) {
    for (var i = 0; i < records.length; i++) {
        var record = records[i];
        var sssid = record.get('sssid');
        var bitindex = record.get('BitIndex');
        if (g_DicTrackerStateDefine.ContainsKey(sssid)) {
            var tmpdic = g_DicTrackerStateDefine.Item(sssid);
            tmpdic.Add(bitindex, record);
        }
        else {
            var tmpdic = new Dictionary();
            tmpdic.Add(bitindex, record);
            g_DicTrackerStateDefine.Add(sssid, tmpdic);

        }
    }
    devicestore.load();
});

function trackerConfigWin() {
    function msgUpdateSuccess(){
        Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
        Ext.Msg.show({
            title: _CustomerConfigResource_Tip,
            msg: _CustomerConfigResource_Success,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.INFO
        });
    };
    
    function msgUpdateFailure(){
        Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
        Ext.Msg.show({
            title: _CustomerConfigResource_Tip,
            msg: _CustomerConfigResource_Failure,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.WARNING
        });
    }
    
    var trackerCombo = getTrackerCheckboxCombo(true);
    
    var typestore = new Ext.data.SimpleStore({
        fields: ['id', 'type'],
        data: [
           ['1', _AlarmResource_SOSButton_Pressed_Input1_Active],
           ['2', _AlarmResource_ButtonB_Pressed_Input2_Active],
           ['3', _AlarmResource_ButtonC_Pressed_Input3_Active],
           ['4', _AlarmResource_Input4_Active],
           ['5', _AlarmResource_Input5_Active],
           ['49', _AlarmResource_SOSButton_Released_Input1_InActive],
           ['50', _AlarmResource_ButtonB_Released_Input2_InActive],
           ['51', _AlarmResource_ButtonC_Released_Input3_InActive],
           ['52', _AlarmResource_Input4_InActive],
           ['53', _AlarmResource_Input5_InActive]
       ]
    });

    var alarmdefinesm = new Ext.grid.CheckboxSelectionModel();
    
    var calculatedefinesm = new Ext.grid.CheckboxSelectionModel();
    
    var statedefinesm = new Ext.grid.CheckboxSelectionModel();
    
    var stateDefinedStore = new Ext.data.SimpleStore({
        fields: ['type', 'data'],
        data: [[_ConfigResource_Output1, 0], [_ConfigResource_Output2, 1], [_ConfigResource_Output3, 2], [_ConfigResource_Output4, 3], [_ConfigResource_Output5, 4], [_ConfigResource_Input1, 8],
                        [_ConfigResource_Input2, 9], [_ConfigResource_Input3, 10], [_ConfigResource_Input4, 11], [_ConfigResource_Input5, 12]]
    })

    //store
    var alarmdefinestore = new Ext.data.JsonStore({
        url: 'HandlerTrackerDefine',
        autoLoad: false,
        root: 'data',
        fields: [
            'sssid',
            'TrackerName',
            {name:'DefineID',type:'integer'}
            ,{ name: 'AlarmType', type: 'integer' }
            , 'Expression',
            , { name: 'IsEmergency', type: 'boolean' }
            , { name: 'SendEmail', type: 'boolean' }
            ]
    });

    var calculatedefinestore = new Ext.data.JsonStore({
        url: 'HandlerTrackerDefine',
        autoLoad: false,
        root: 'data',
        fields: [
        'sssid',
        'TrackerName',
        { name: 'DefineID', type: 'integer' },
        'Expression',
        'Calculate',
        { name: 'ShowType', type: 'integer' },
        { name: 'ControlType', type: 'integer' },
        'SensorName',
        { name: 'SensorID', type: 'integer' }
        ]
    });

    var statedefinestore = new Ext.data.JsonStore({
        url: 'HandlerTrackerDefine',
        autoLoad: false,
        root: 'data',
        fields: [
        'sssid',
        'TrackerName',
        { name: 'DefineID', type: 'integer' },
        { name:'BitIndex', type: 'integer' },
        'Expression',
        { name: 'ControlType', type: 'integer' },
        'true_exp',
        'false_exp']
    });

    TrackerDefine.AlarmGrid = Ext.extend(Ext.grid.EditorGridPanel, {
        initComponent: function() {
            this.action = new Ext.ux.grid.RowActions({
                header: ''
                  , autoWidth: true
                //          ,hideMode:'display'
                , keepSelection: false
                , actions: [{
                    iconCls: 'icon-led-edit'
                    , tooltip: _LED_EditAdv
                    }, {
                        iconCls: 'icon-led-del'
                        , tooltip: _CustomerConfigResource_Delete
                    }]
                , callbacks: {
                    'icon-led-edit': function(grid, record, action, row, col) {

                    }
                    }
                });
                this.action.on({
                    action: function(grid, record, action, row, col) {
                        //Ext.ux.Toast.msg('Event: action', 'You have clicked row: <b>{0}</b>, action: <b>{1}</b>', row, action);
                        if (action == 'icon-led-edit') {
                            addEditTrackerAlarmDefineWin(record);
                        }
                        else if (action == 'icon-led-del') {
                            Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                            Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn) {
                                if (btn == "yes") {
                                    Ext.Ajax.request({
                                        url: 'HandlerTrackerDefine',
                                        success: function(result) {
                                            Ext.MessageBox.hide();
                                            var flag = eval(result.responseText);
                                            if (flag != "false") {
                                                alarmdefinestore.remove(record);
                                                getAlarmDefine();
                                                Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted);
                                            }
                                            else {
                                                msgUpdateFailure();
                                            }
                                        },
                                        failure: function() {
                                            Ext.MessageBox.hide();
                                            msgUpdateFailure();
                                        },
                                        params: {
                                            autoids: record.get('DefineID'),
                                            eventtype: 'delete',
                                            eventobject: 'alarm'
                                        }
                                    });

                                }
                            });
                        }
                    }
                });
                Ext.apply(this, {
                    colModel: new Ext.grid.ColumnModel({
                        columns: [
                            alarmdefinesm,
                            this.action,
                            {
                                header: _TrackerMain_TrackerName,
                                dataIndex: 'TrackerName',
                                width: 200
                            }, {
                                header: _CustomerConfigResource_AlarmType,
                                dataIndex: 'AlarmType',
                                width: 230,
                                renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                                    var index = typestore.find('id', value);
                                    if (index != -1) {
                                        return typestore.getAt(index).data.type;
                                    }
                                }
                            }, {
                                header: _CustomerConfigResource_Expression,
                                dataIndex: 'Expression',
                                width: 150
                            }, {
                                header:_TrackerMain_Emergency,
                                dataIndex: 'IsEmergency',
                                width: 60,
                                renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                                    if (value)
                                        return _TrackerMain_Yes;
                                    else
                                        return _TrackerMain_No;
                                }
                            },{
                                header: _TrackerMain_EmailAlarm,
                                dataIndex: 'SendEmail',
                                width: 60,
                                renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                                    if (value)
                                        return _TrackerMain_Yes;
                                    else
                                        return _TrackerMain_No;
                                }
                            }
                        ],
                        defaults: {
                            sortable: true,
                            menuDisabled: true,
                            width: 75
                        }
                    }),
                    plugins: [this.action],
                    stripeRows: true,
                    listeners: {
                        load: { scope: this, fn: function() {
                            this.getSelectionModel().selectFirstRow();
                        }
                        }
                    }
                });
                TrackerDefine.AlarmGrid.superclass.initComponent.apply(this, arguments);
            }
        , onRender: function() {
            TrackerDefine.AlarmGrid.superclass.onRender.apply(this, arguments);

        }
        });

    var alarmdefinegrid = new TrackerDefine.AlarmGrid({
        store: alarmdefinestore,
        //cm: alarmdefinecm,
        sm: alarmdefinesm,
        loadMask: true,
        width: 500,
        height: 350,
        enableHdMenu: false,
        frame: true,
        clicksToEdit: 2,
        tbar: [{
            text: _CustomerConfigResource_AddNew,
            icon: 'images/add.png',
            handler: function() {
                addEditTrackerAlarmDefineWin();
            }
        } 
//        ,{
//            text: _TxtEdit,
//            icon: 'images/edit.gif',
//            handler: function() {
//                var records = alarmdefinegrid.getSelectionModel().getSelections();

//            }
//        }
        , {
            ref: '../removeBtn',
            disabled: true,
            text: _CustomerConfigResource_Delete,
            icon: 'images/delete.png',
            handler: function() {
                Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn) {
                    if (btn == "yes") {
                        Ext.MessageBox.show({
                            msg: _CustomerConfigResource_Deleting,
                            progressText: _CustomerConfigResource_Deleting,
                            width: 300,
                            wait: true,
                            waitConfig: { interval: 200 }
                        });
                        var s = alarmdefinegrid.getSelectionModel().getSelections();
                        var splitIds = "";
                        for (var j = 0; j < s.length; j++) {
                            if (s.length == 1) {
                                splitIds = s[j].data.DefineID;
                            }
                            else {

                                if (j < (s.length - 1)) {
                                    splitIds = s[j].data.DefineID + "," + splitIds;
                                }
                                if (j == (s.length - 1)) {
                                    splitIds = splitIds + s[j].data.DefineID;
                                }
                            }
                        }
                        Ext.Ajax.request({
                            url: 'HandlerTrackerDefine',
                            success: function(result) {
                                Ext.MessageBox.hide();
                                var flag = eval(result.responseText);
                                if (flag != "false") {
                                    for (var i = 0, r; r = s[i]; i++) {
                                        alarmdefinestore.remove(r);
                                        getAlarmDefine();
                                        Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted)
                                    }
                                }
                                else {
                                    msgUpdateFailure();
                                }
                            },
                            failure: function() {
                                Ext.MessageBox.hide();
                                msgUpdateFailure();
                            },
                            params: {
                                autoids: splitIds,
                                eventtype: 'delete',
                                eventobject: 'alarm'
                            }
                        })
                    }
                });
            }
        }]
    });
        
    alarmdefinegrid.getSelectionModel().on('selectionchange', function(sm) {
        alarmdefinegrid.removeBtn.setDisabled(sm.getCount() < 1);
    });

    TrackerDefine.SensorGrid = Ext.extend(Ext.grid.EditorGridPanel, {
        initComponent: function() {
            this.action = new Ext.ux.grid.RowActions({
                header: ''
                  , autoWidth: true
                //          ,hideMode:'display'
                , keepSelection: false
                , actions: [{
                    iconCls: 'icon-led-edit'
                    , tooltip: _LED_EditAdv
                }, {
                    iconCls: 'icon-led-del'
                        , tooltip: _CustomerConfigResource_Delete
}]
                , callbacks: {
                    'icon-led-edit': function(grid, record, action, row, col) {

                    }
                }
                });
                this.action.on({
                    action: function(grid, record, action, row, col) {
                        //Ext.ux.Toast.msg('Event: action', 'You have clicked row: <b>{0}</b>, action: <b>{1}</b>', row, action);
                        if (action == 'icon-led-edit') {
                            addEditTrackerSensorDefineWin(record);
                        }
                        else if (action == 'icon-led-del') {
                            Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                            Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn) {
                                if (btn == "yes") {
                                    Ext.Ajax.request({
                                        url: 'HandlerTrackerDefine',
                                        success: function(result) {
                                            Ext.MessageBox.hide();
                                            var flag = eval(result.responseText);
                                            if (flag != "false") {
                                                calculatedefinestore.remove(record);
                                                //getUserDefineFieldsNames();
                                                Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted);

                                            }
                                            else {
                                                msgUpdateFailure();
                                            }
                                        },
                                        failure: function() {
                                            Ext.MessageBox.hide();
                                            msgUpdateFailure();
                                        },
                                        params: {
                                            autoids: record.get('DefineID'),
                                            eventtype: 'delete',
                                            eventobject: 'sensor'
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
                Ext.apply(this, {
                    colModel: new Ext.grid.ColumnModel({
                        columns: [
                            calculatedefinesm,
                            this.action,
                            {
                                header: _TrackerMain_TrackerName,
                                dataIndex: 'TrackerName',
                                width: 230
                            }, {
                                header: _CustomerConfigResource_Expression,
                                dataIndex: 'Expression',
                                width: 120
                            }, {
                                header: _CustomerConfigResource_Calculate,
                                dataIndex: 'Calculate',
                                width: 150
                            }, {
                                header: _CustomerConfigResource_SensorName,
                                dataIndex: 'SensorTableId',
                                width: 120,
                                hidden: true
                            }, {
                                header: _CustomerConfigResource_ShowType,
                                dataIndex: 'ShowType',
                                width: 70
                                , renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                                    if (value == 0) {
                                        return _CustomerConfigResource_Decimal;
                                    }
                                    else if (value == 1) {
                                        return _CustomerConfigResource_Percent;
                                    }
                                }
                            }
                        ],
                        defaults: {
                            sortable: true,
                            menuDisabled: true,
                            width: 75
                        }
                    }),
                    plugins: [this.action],
                    stripeRows: true,
                    listeners: {
                        load: { scope: this, fn: function() {
                            this.getSelectionModel().selectFirstRow();
                        }
                        }
                    }
                });
                TrackerDefine.AlarmGrid.superclass.initComponent.apply(this, arguments);
            }
            , onRender: function() {
                TrackerDefine.AlarmGrid.superclass.onRender.apply(this, arguments);

            }
        });
        
        var calculatedefinegrid = new TrackerDefine.SensorGrid({
            store: calculatedefinestore,
            //cm: calculatedefinecm,
            sm: calculatedefinesm,
            loadMask: true,
            width: 500,
            height: 350,
            frame: true,
            enableHdMenu: false,
            clicksToEdit: 2,
            tbar: [{
                text: _CustomerConfigResource_AddNew,
                icon: 'images/add.png',
                handler: function() {
                    addEditTrackerSensorDefineWin();
                }
            }
    //        , {
    //            text: _TxtEdit,
    //            icon: 'images/edit.gif',
    //            handler: function() {
    //                var records = alarmdefinegrid.getSelectionModel().getSelections();
    //                addEditTrackerSensorDefineWin(records);
    //            }
    //        }
            , {
                ref: '../removeBtn',
                disabled: true,
                text: _CustomerConfigResource_Delete,
                icon: 'images/delete.png',
                handler: function() {
                    Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                    Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn){
                        if (btn == "yes") {
                        
                        Ext.MessageBox.show({
                            msg: _CustomerConfigResource_Deleting,
                            progressText: _CustomerConfigResource_Deleting,
                            width: 300,
                            wait: true,
                            waitConfig: { interval: 200 }
                        });
                        var s = calculatedefinegrid.getSelectionModel().getSelections();
                        var splitIds = "";
                        for (var j = 0; j < s.length; j++) {
                            if (s.length == 1) {
                                splitIds = s[j].data.DefineID;
                            }
                            else {

                                if (j < (s.length - 1)) {
                                    splitIds = s[j].data.DefineID + "," + splitIds;
                                }
                                if (j == (s.length - 1)) {
                                    splitIds = splitIds + s[j].data.DefineID;
                                }
                            }
                        }
                        Ext.Ajax.request({
                            url: 'HandlerTrackerDefine',
                            success: function(result) {
                                Ext.MessageBox.hide();
                                var flag = eval(result.responseText);
                                if (flag != "false") {
                                    for (var i = 0, r; r = s[i]; i++) {
                                        calculatedefinestore.remove(r);
                                        //getUserDefineFieldsNames();
                                        Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted)
                                    }

                                }
                                else {
                                    Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Added)
                                }
                            },
                            failure: function() {
                                Ext.MessageBox.hide();
                                Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Added)
                            },
                            params: {
                                autoids: splitIds,
                                eventtype: 'delete',
                                eventobject:'sensor'
                            }
                            })
                        }
                    });
                }
            }]
        });
        
        calculatedefinegrid.getSelectionModel().on('selectionchange', function(sm) {
            calculatedefinegrid.removeBtn.setDisabled(sm.getCount() < 1);
        });

        TrackerDefine.StateGrid = Ext.extend(Ext.grid.EditorGridPanel, {
            initComponent: function() {
                this.action = new Ext.ux.grid.RowActions({
                    header: ''
                  , autoWidth: true
                    //          ,hideMode:'display'
                , keepSelection: false
                , actions: [{
                    iconCls: 'icon-led-edit'
                    , tooltip: _LED_EditAdv
                }, {
                    iconCls: 'icon-led-del'
                        , tooltip: _CustomerConfigResource_Delete
}]
                , callbacks: {
                    'icon-led-edit': function(grid, record, action, row, col) {

                    }
                }
                });
                this.action.on({
                    action: function(grid, record, action, row, col) {
                        //Ext.ux.Toast.msg('Event: action', 'You have clicked row: <b>{0}</b>, action: <b>{1}</b>', row, action);
                        if (action == 'icon-led-edit') {
                            addEditTrackerStateDefineWin(record);
                        }
                        else if (action == 'icon-led-del') {
                            Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                            Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn) {
                                if (btn == "yes") {
                                    Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                                    Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn) {
                                        if (btn == "yes") {
                                            Ext.Ajax.request({
                                                url: 'HandlerTrackerDefine',
                                                success: function(result) {
                                                    Ext.MessageBox.hide();
                                                    var flag = eval(result.responseText);
                                                    if (flag != "false") {
                                                        statedefinestore.remove(record);
                                                        //getUserDefineFieldsNames();
                                                        Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted);

                                                    }
                                                    else {
                                                        msgUpdateFailure();
                                                    }
                                                },
                                                failure: function() {
                                                    Ext.MessageBox.hide();
                                                    msgUpdateFailure();
                                                },
                                                params: {
                                                    autoids: record.get('DefineID'),
                                                    eventtype: 'delete',
                                                    eventobject: 'state'
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
                Ext.apply(this, {
                    colModel: new Ext.grid.ColumnModel({
                        columns: [
                            statedefinesm,
                            this.action,
                            {
                                header: _TrackerMain_TrackerName,
                                dataIndex: 'TrackerName',
                                width: 230
                            }, {
                                header: _CustomerConfigResource_BitIndex,
                                dataIndex: 'BitIndex',
                                width: 120
                                , renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                                    var index = stateDefinedStore.find('data', value);
                                    if (index != -1) {
                                        return stateDefinedStore.getAt(index).data.type;
                                    }
                                }
                            }, {
                                header: _CustomerConfigResource_Expression,
                                dataIndex: 'Expression',
                                width: 110
                            }, {
                                header: _CustomerConfigResource_True_exp,
                                dataIndex: 'true_exp',
                                width: 110
                            }, {
                                header: _CustomerConfigResource_False_exp,
                                dataIndex: 'false_exp',
                                width: 110
                            }
                        ],
                        defaults: {
                            sortable: true,
                            menuDisabled: true,
                            width: 75
                        }
                    }),
                    plugins: [this.action],
                    stripeRows: true,
                    listeners: {
                        load: { scope: this, fn: function() {
                            this.getSelectionModel().selectFirstRow();
                        }
                        }
                    }
                });
                TrackerDefine.AlarmGrid.superclass.initComponent.apply(this, arguments);
            }
            , onRender: function() {
                TrackerDefine.AlarmGrid.superclass.onRender.apply(this, arguments);

            }
        });

        var statedefinegrid = new TrackerDefine.StateGrid({
            store: statedefinestore,
            //cm: statedefinecm,
            sm: statedefinesm,
            width: 500,
            height: 350,
            loadMask: true,
            enableHdMenu: false,
            frame: true,
            clicksToEdit: 2,
            tbar: [{
                text: _CustomerConfigResource_AddNew,
                icon: 'images/add.png',
                handler: function() {
                    addEditTrackerStateDefineWin();
                }
            }
    //        , {
    //            text: _TxtEdit,
    //            icon: 'images/edit.gif',
    //            handler: function() {
    //                var records = statedefinegrid.getSelectionModel().getSelections();
    //                addEditTrackerStateDefineWin(records);
    //            }
    //        }
            , {
                ref: '../removeBtn',
                disabled: true,
                text: _CustomerConfigResource_Delete,
                icon: 'images/delete.png',
                handler: function() {
                    Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                    Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn){
                        if (btn == "yes") {
                            Ext.MessageBox.show({
                                msg: _CustomerConfigResource_Deleting,
                                progressText: _CustomerConfigResource_Deleting,
                                width: 300,
                                wait: true,
                                waitConfig: { interval: 200 }
                            });
                            var s = statedefinegrid.getSelectionModel().getSelections();
                            var splitIds = "";
                            for (var j = 0; j < s.length; j++) {
                                if (s.length == 1) {
                                    splitIds = s[j].data.DefineID;
                                }
                                else {

                                    if (j < (s.length - 1)) {
                                        splitIds = s[j].data.DefineID + "," + splitIds;
                                    }
                                    if (j == (s.length - 1)) {
                                        splitIds = splitIds + s[j].data.DefineID;
                                    }
                                }
                            }
                            Ext.Ajax.request({
                                url: 'HandlerTrackerDefine',
                                success: function(result) {
                                    Ext.MessageBox.hide();
                                    var flag = eval(result.responseText);
                                    if (flag != "false") {
                                        for (var i = 0, r; r = s[i]; i++) {
                                            statedefinestore.remove(r);
                                            getUserDefineFieldsNames();
                                            Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted)
                                        }

                                    }
                                    else {
                                        msgUpdateFailure();
                                    }
                                },
                                failure: function() {
                                    Ext.MessageBox.hide();
                                    msgUpdateFailure();
                                },
                                params: {
                                    autoids: splitIds,
                                    eventtype: 'delete',
                                    eventobject:'state'
                                }
                            })
                        }
                    });
                }
            }]
        });
    
        statedefinegrid.getSelectionModel().on('selectionchange', function(sm) {
            statedefinegrid.removeBtn.setDisabled(sm.getCount() < 1);
        });

        var txtkeywords = new Ext.form.TextField({
        });

    var tp = new Ext.TabPanel({
        height: 380,
        width: 500,
        activeTab: 0,
        tbar: [_Alarm_Header_Name,
            trackerCombo,
            _TrackerMain_Keywords,
            txtkeywords,
            {
                text: _TrackerMain_SearchDefined,
                icon: 'images/search16.gif',
                handler: function() {
                    var sssids = trackerCombo.getValue();
                    var index = tp.items.findIndex('id',tp.getActiveTab().id);
                    var eventobject = 'alarm';
                    if (index == 0) {
                        eventobject = 'alarm';
                        alarmdefinestore.load({
                            params: {
                                sssids: sssids,
                                eventtype: 'search',
                                eventobject: eventobject,
                                key: txtkeywords.getValue()
                            }
                        });
                    }
                    else if (index == 1) {
                        eventobject = 'state';
                        statedefinestore.load({
                            params: {
                                sssids: sssids,
                                eventtype:'search',
                                eventobject: eventobject,
                                key: txtkeywords.getValue()
                            }
                        });
                    }
                    else if (index == 2) {
                        eventobject = 'sensor';
                        calculatedefinestore.load({
                            params: {
                                sssids: sssids,
                                eventtype:'search',
                                eventobject: eventobject,
                                key: txtkeywords.getValue()
                            }
                        });
                    }

                }
        }],
        items: [{
            title: _CustomerConfigResource_AlarmDefine,
            iconCls: 'icon-alarmdefine',
            layout: 'fit',
            items: [alarmdefinegrid],
            activeTab: 0
        }, {
            iconCls: 'icon-statedefine',
            title: _CustomerConfigResource_StateDefine,
            layout: 'fit',
            items: [statedefinegrid]
        }, {
            iconCls: 'icon-calculatedefine',
            title: _CustomerConfigResource_CalculateDefine,
            layout: 'fit',
            items: [calculatedefinegrid]
}]
        });

    var trackerConfigWindow = new Ext.Window({
        title :_TrackerMain_TrackerConfig,
        iconCls:'icon-trackerdefine',
        width: 820,
        height: 520,
        resizable: true,
        plain: true,
        layout:'fit',
        closeAction: 'close',
        items: [tp],
        minimizable: true,
        constrain:true,
        listeners: {
            'minimize': function() {
                addTaskButtonForWindow(trackerConfigWindow);
            }
        }
    });
    
    trackerConfigWindow.show();
}


function addEditTrackerAlarmDefineWin(alarmdefinerecord){
    function msgUpdateSuccess() {
        Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
        Ext.Msg.show({
            title: _TrackerMain_Title,
            msg: _NewForText_Success,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.INFO
        });
    }
    
    function msgWarning(msgtext) {
        Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
        Ext.Msg.show({
            title: _TrackerMain_Title,
            msg: msgtext,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.WARNING
        });
    }
    
    function msgUpdateFailure() {
        Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
        Ext.Msg.show({
            title: _TrackerMain_Title,
            msg: _NewForText_Failure,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.WARNING
        });
    }


    var trackNameCombo = getTrackerCheckboxCombo(true);
    trackNameCombo.setWidth(240);
    
    var alarmtypestore = new Ext.data.SimpleStore({
        fields: ['id', 'type'],
        data: [
           ['1', _AlarmResource_SOSButton_Pressed_Input1_Active],
           ['2', _AlarmResource_ButtonB_Pressed_Input2_Active],
           ['3', _AlarmResource_ButtonC_Pressed_Input3_Active],
           ['4', _AlarmResource_Input4_Active],
           ['5', _AlarmResource_Input5_Active],
           ['49', _AlarmResource_SOSButton_Released_Input1_InActive],
           ['50', _AlarmResource_ButtonB_Released_Input2_InActive],
           ['51', _AlarmResource_ButtonC_Released_Input3_InActive],
           ['52', _AlarmResource_Input4_InActive],
           ['53', _AlarmResource_Input5_InActive]
       ]
    });
    
    var alarmTypeCombo = new Ext.form.ComboBox({
       fieldLabel:_CustomerConfigResource_AlarmType,
        triggerAction: 'all',
        lazyRender: true,
        store: alarmtypestore,
        displayField: 'type',
        width: 240,
        mode: 'local',
        valueField: 'id',
        editable: false
    });
    
    var txtInputAlarmExpression =new Ext.form.TextField({
        allowBlank: false,
        blankText: _CustomerConfigResource_CanNotEmpty,
        fieldLabel: _CustomerConfigResource_Expression,
        width:240
    });

    var chkIsEmergency = new Ext.form.Checkbox({
        value: true,
        fieldLabel: _TrackerMain_Emergency
    });
    
    var chkSendEmail = new Ext.form.Checkbox({
        value:true,
        fieldLabel: _TrackerMain_EmailAlarm
    });

    if (Ext.isDefined(alarmdefinerecord)) {
        trackNameCombo.setVisible(false);
        alarmTypeCombo.setValue(alarmdefinerecord.get('AlarmType'));
        txtInputAlarmExpression.setValue(alarmdefinerecord.get('Expression'));
        chkIsEmergency.setValue(alarmdefinerecord.get('IsEmergency'));
        chkSendEmail.setValue(alarmdefinerecord.get('SendEmail'));
    }
   
    var trackerAlarmDefinePanel = new Ext.form.FormPanel({
        bodyStyle: "padding-top:10px;padding-left:10px",
        width: 380,
        height: 180,
        defaultType: "textfield",
        items: [
            trackNameCombo,
            alarmTypeCombo,
            txtInputAlarmExpression,
            chkIsEmergency,
            chkSendEmail
        ],
        buttons: [{ text: _NewForText_Submit,
                handler: function() {
                    if (trackerAlarmDefinePanel.getForm().isValid()) {
                        Ext.MessageBox.show({
                            msg: _NewForText_Saving,
                            progressText: _NewForText_Saving + '...',
                            width: 300,
                            wait: true,
                            waitConfig: { interval: 200 },
                            icon: 'download'
                        });
                        trackerAlarmDefinePanel.form.submit({
                            url: "HandlerTrackerDefine",
                            method: "POST",
                            params: {
                                eventtype: 'add',
                                eventobject: 'alarm',
                                sssids: Ext.isDefined(alarmdefinerecord) ? alarmdefinerecord.get('sssid') : trackNameCombo.getValue(),
                                definedid: Ext.isDefined(alarmdefinerecord) ? alarmdefinerecord.get('DefineID') : 0,
                                IsEmergency:chkIsEmergency.getValue(),
                                AlarmTypeId:alarmTypeCombo.getValue(),
                                Expression:txtInputAlarmExpression.getValue(),
                                SendEmail:chkSendEmail.getValue()
                            },
                            success: function(form, action) {
                                //after success
                                var flag = action.result.success;
                                if (flag == true) {
                                    msgUpdateSuccess();
                                    win.hide();
                                }
                                else if (flag == "iserror") {
                                    msgWarning(_NewForText_AddNewDeviceFailedByExist);
                                }
                                
                            },
                            failure: function(form, action) {
                                msgUpdateFailure();
                            }
                        })
                    }
                }
            }]
        });
        
        
        var win = new Ext.Window({
            title: _CustomerConfigResource_AlarmDefine,
            height: 210,
            closeAction: 'hide',
            width: 400,
            plain: true,
            modal: 'true',
            buttonAlign: "center",
            constrain:true,
            items: [trackerAlarmDefinePanel]
        });

        win.show();
}

function addEditTrackerStateDefineWin(statedefinerecord) {

    var stateDefinedStore = new Ext.data.SimpleStore({
        fields: ['type', 'data'],
        data: [[_ConfigResource_Output1, 0], [_ConfigResource_Output2, 1], [_ConfigResource_Output3, 2], [_ConfigResource_Output4, 3], [_ConfigResource_Output5, 4], [_ConfigResource_Input1, 8],
                        [_ConfigResource_Input2, 9], [_ConfigResource_Input3, 10], [_ConfigResource_Input4, 11], [_ConfigResource_Input5, 12]]
    });

    var trackNameCombo = getTrackerCheckboxCombo(true);
    trackNameCombo.setWidth(240);

    var cmbStateIndex = new Ext.form.ComboBox({
        fieldLabel: _CustomerConfigResource_BitIndex,
        editable: false,
        triggerAction: 'all',
        store: stateDefinedStore,
        displayField: 'type',
        width: 240,
        mode: 'local',
        valueField: 'data'
    });

    var txtStateExpression = new Ext.form.TextField({
        fieldLabel:_CustomerConfigResource_Expression,
        allowBlank: false,
        width: 240,
        blankText: _CustomerConfigResource_CanNotEmpty
    });

    var txtTrueExpression = new Ext.form.TextField({
        fieldLabel:_CustomerConfigResource_True_exp,
        width: 240,
        allowBlank: false,
        blankText: _CustomerConfigResource_CanNotEmpty
    });

    var txtFalseExpresson = new Ext.form.TextField({
        fieldLabel:_CustomerConfigResource_False_exp,
        width: 240,
        allowBlank: false,
        blankText: _CustomerConfigResource_CanNotEmpty
    });


    if (Ext.isDefined(statedefinerecord)) {
        trackNameCombo.setVisible(false);
        txtStateExpression.setValue(statedefinerecord.get('Expression'));
        cmbStateIndex.setValue(statedefinerecord.get('BitIndex'));
        txtTrueExpression.setValue(statedefinerecord.get('true_exp'));
        txtFalseExpresson.setValue(statedefinerecord.get('false_exp'));
    }
    
    var trackerStateDefinePanel = new Ext.form.FormPanel({
        bodyStyle: "padding-top:10px;padding-left:10px",
        width: 380,
        height: 180,
        defaultType: "textfield",
        items: [
            trackNameCombo,
            cmbStateIndex,
            txtStateExpression,
            txtTrueExpression,
            txtFalseExpresson
        ],
        buttons: [{ text: _NewForText_Submit,
                handler: function() {
                    if (trackerStateDefinePanel.getForm().isValid()) {
                        Ext.MessageBox.show({
                            msg: _NewForText_Saving,
                            progressText: _NewForText_Saving + '...',
                            width: 300,
                            wait: true,
                            waitConfig: { interval: 200 },
                            icon: 'download'
                        });
                        trackerStateDefinePanel.form.submit({
                            url: "HandlerTrackerDefine",
                            method: "POST",
                            params: {
                                eventtype: 'add',
                                eventobject: 'state',
                                sssids: Ext.isDefined(statedefinerecord) ? statedefinerecord.get('sssid') : trackNameCombo.getValue(),
                                definedid: Ext.isDefined(statedefinerecord) ? statedefinerecord.get('DefineID') : 0,
                                bitindex: cmbStateIndex.getValue(),
                                expression: txtStateExpression.getValue(),
                                trueexpression: txtTrueExpression.getValue(),
                                falseexpression: txtFalseExpresson.getValue()
                            },
                            success: function(form, action) {
                                //after success
                                var flag = action.result.success;
                                if (flag == true) {
                                    msgUpdateSuccess();
                                    win.hide();
                                }
                                else if (flag == "iserror") {
                                    msgWarning(_NewForText_AddNewDeviceFailedByExist);
                                }

                            },
                            failure: function(form, action) {
                                msgUpdateFailure();
                            }
                        })
                    }
                }
            }]
        });
    var win = new Ext.Window({
        title: _CustomerConfigResource_StateDefine,
        height: 210,
        closeAction: 'hide',
        width: 400,
        plain: true,
        modal: 'true',
        buttonAlign: "center",
        constrain: true,
        items: [trackerStateDefinePanel]
    });

    win.show();
}

function addEditTrackerSensorDefineWin(sensordefinerecord) {
    var trackNameCombo = getTrackerCheckboxCombo(true);
    trackNameCombo.setWidth(240);
    
    var txtExpression = new Ext.form.TextField({
        fieldLabel: _CustomerConfigResource_Expression,
        allowBlank: false,
        blankText: _CustomerConfigResource_CanNotEmpty
    });

    var txtCalculate = new Ext.form.TextField({
        fieldLabel: _CustomerConfigResource_Calculate,
        allowBlank: true,
        //blankText: _CustomerConfigResource_CanNotEmpty,
        validator: validCalculate,
        invalidText: _CustomerConfigResource_CValidError
    });

    var cmbNotLineSensor = new Ext.form.ComboBox({
        fieldLabel:_CustomerConfigResource_SensorName,
        editable: false,
        triggerAction:'all',
        store: new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'HandlerGetAllSensorName',
                timeout: 10000
            }),
            reader: new Ext.data.JsonReader({
                fields: ['sensorid', 'sensorname'],
                root: "data"
            }),
            autoLoad: true
        }),
        displayField: 'sensorname',
        width: 120,
        mode: 'local',
        valueField: 'sensorname',
        listeners: { select: function(combo, record, index) {
                var store = sensorCombox.getStore();
                try {
                    sensorid = store.data.items[index].data.sensorid;
                }
                catch (Error) {
                    sensorid = null;
                }
            }
        }
    });

    var sensorCombox = new Ext.form.ComboBox({
        editable: false,
        triggerAction: 'all',
        store: new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'HandlerGetAllSensorName',
                timeout: 10000
            }),
            reader: new Ext.data.JsonReader({
                fields: ['sensorid'],
                root: "data"
            }),
            autoLoad: true
        }),
        displayField: 'sensorid',
        width: 120,
        mode: 'local',
        valueField: 'sensorid'
    });


    var cmbDataType = new Ext.form.ComboBox({
        fieldLabel:_CustomerConfigResource_ShowType,
        editable: false,
        triggerAction: 'all',
        store: new Ext.data.SimpleStore({
            fields: ['index', 'type'],
            data: [['0', _CustomerConfigResource_Decimal], ['1', _CustomerConfigResource_Percent]]
        }),
        displayField: 'type',
        width: 240,
        mode: 'local',
        valueField: 'index'
    });

    cmbDataType.setValue('0');

    if (Ext.isDefined(sensordefinerecord)) {
        trackNameCombo.setVisible(false);
        txtExpression.setValue(sensordefinerecord.get('Expression'));
        txtCalculate.setValue(sensordefinerecord.get('Calculate'));
        cmbDataType.setValue(sensordefinerecord.get('ShowType'));
        
    }
    
    function validCalculate(mathstring) {
        if (mathstring.toUpperCase().indexOf(',') != -1)
            return false;
        var matharray = mathstring.split('AD');
        if (mathstring.toUpperCase().indexOf('AD') != -1 && mathstring.length > 2) {
            for (var j = 0; j < matharray.length; j++) {
                if (j > 0) {
                    if (matharray[j].charAt(0) > 8)
                        return false;
                }
                var param = "-" + matharray[j].substring(matharray[j].length - 1, matharray[j].length);
                var pchar = param.charAt(param.length - 1);
                if (j != matharray.length - 1) {
                    if (pchar >= '0' && pchar <= '9') {
                        return false
                    }
                }
                else {
                    var pchar1;
                    if (matharray[j].length >= 2) {
                        pchar1 = matharray[j].charAt(1);
                        if (pchar1 >= '0' && pchar1 <= '9') {
                            return false
                        }
                    }
                    else {

                    }
                }
            }
            var newmathstring = "";
            for (var i = 0; i < matharray.length; i++) {
                newmathstring += matharray[i];
            }

            //mathstring= mathstring.replace(mathstring.substring(mathstring.toUpperCase().indexOf('AD'),mathstring.toUpperCase().indexOf('AD')+2),'1')
            try {
                if (eval(newmathstring) == undefined)
                    return false;
                else {
                    return true
                }
            }
            catch (err) {
                return false
            }
        }
        else {
            return false;
        }
    };

    var trackerSensorDefinePanel = new Ext.form.FormPanel({
        bodyStyle: "padding-top:10px;padding-left:10px",
        width: 380,
        height: 180,
        defaultType: "textfield",
        items: [
            trackNameCombo,
            txtExpression,
            txtCalculate,
            cmbNotLineSensor,
            cmbDataType
        ],
        buttons: [{ text: _NewForText_Submit,
            handler: function() {
            if (trackerSensorDefinePanel.getForm().isValid()) {
                    Ext.MessageBox.show({
                        msg: _NewForText_Saving,
                        progressText: _NewForText_Saving + '...',
                        width: 300,
                        wait: true,
                        waitConfig: { interval: 200 },
                        icon: 'download'
                    });
                    trackerSensorDefinePanel.form.submit({
                        url: "HandlerTrackerDefine",
                        method: "POST",
                        params: {
                            eventtype: 'add',
                            eventobject: 'sensor',
                            sssids: Ext.isDefined(sensordefinerecord) ? sensordefinerecord.get('sssid') : trackNameCombo.getValue(),
                            definedid: Ext.isDefined(sensordefinerecord) ? sensordefinerecord.get('DefineID'):0,
                            expression: txtExpression.getValue(),
                            calculate: txtCalculate.getValue(),
                            notlinesensor: cmbNotLineSensor.getValue(),
                            datatype: cmbDataType.getValue()
                        },
                        success: function(form, action) {
                            //after success
                            var flag = action.result.success;
                            if (flag == true) {
                                msgUpdateSuccess();
                                win.hide();
                            }
                            else if (flag == "iserror") {
                                msgWarning(_NewForText_AddNewDeviceFailedByExist);
                            }

                        },
                        failure: function(form, action) {
                            msgUpdateFailure();
                        }
                    })
                }
            }
        }]
        });
        var win = new Ext.Window({
            title: _CustomerConfigResource_CalculateDefine,
            height: 210,
            closeAction: 'hide',
            width: 400,
            plain: true,
            modal: 'true',
            buttonAlign: "center",
            constrain: true,
            items: [trackerSensorDefinePanel]
        });

        win.show();
}